<template>
  <!-- 大盒子 -->
  <div class="MedicenCata">
    <!-- 主体内容 -->
    <div class="main">
      <!-- left -->
      <!-- right -->
      <div class="main-right" ref="mainRight">
        <div class="main-icon"
             style="display: flex; align-items: center; padding: 8px 10px; background: #fff; border-bottom: 1px solid #ebeef5;">
          <!-- 左侧图标和标题 -->
          <div class="main-icon-a" style="display: flex; align-items: center; margin-right: 15px;">
            <i :class="iconComes"
               style="border-radius: 50%; font-size: 20px; padding: 6px; background-color: #5a5a5a; color: #fff;"></i>
            <span style="font-size: 12px; font-weight: bold; margin-left: 8px; color: #606266;">{{
                CatalogueName
              }}</span>
          </div>

          <!-- 中间区域（所有筛选条件和按钮都在一行） -->
          <div style="display: flex; align-items: center; flex-wrap: nowrap;">
            <!-- 状态下拉 -->
            <div class="main-icon-b" style="margin-right: 20px;">
              <span style="font-size: 12px; color: #606266; font-weight: bold;">状态:</span>
              <el-dropdown @command="handleCommand" trigger="click" style="margin-left: 4px;">
                <span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="d" dropdown>全部</el-dropdown-item>
                  <el-dropdown-item command="c">未作废</el-dropdown-item>
                  <el-dropdown-item command="a">已作废原单</el-dropdown-item>
                  <el-dropdown-item command="b">作废负单</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>

            <!-- 搜索框 -->
            <div style="display: flex; align-items: center; margin-right: 20px; white-space: nowrap;">
              <span style="font-size: 12px; color: #606266; font-weight: bold; margin-right: 8px;">关键字:</span>
              <el-input v-model="queryConditionForm.name" size="mini" style="width: 180px;"
                        @keyup.enter.native="loadData"></el-input>
            </div>

            <div class="block">
              <el-date-picker
                  size="mini"
                  v-model="queryConditionForm.timeFrameArr"
                  type="datetimerange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleConditionQuery"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </div>

            <!-- 按钮组（直接跟在时间选择器后面） -->
            <div style="display: flex; align-items: center;">
              <el-button
                  v-for="(v,i) in headerBtn"
                  :key="i"
                  :type="v.type"
                  :loading="loading"
                  :icon="v.icon"
                  size="mini"
                  :style="{...v.style, 'margin-left': '6px'}"
                  @click="handClick(i)">
                {{ v.title }}
              </el-button>
            </div>
          </div>
        </div>
        <!-- table -->
        <div class="table">
          <el-table :data="tableData"
                    border
                    :summary-method="getSummaries"
                    @row-dblclick="handleDbShowData"
                    show-summary>
            <el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop"
                             :label="col.name" :render-header="labelHead"
                             :min-width="getColumnWidth(col.label,col.prop,tableData)">
              <template #default="{ row }">
                {{ safeGetMappedValue(col, row) }}
              </template>
            </el-table-column>
            <el-table-column fixed="left" label="行号" type="index"></el-table-column>
            <el-table-column fixed="right" label="操作" width="230">
              <template slot-scope="scope">
                <div class="editbox" style="text-align: center;">
                  <el-button type="primary" @click="editReservation(scope.row)" size="mini"
                             :disabled="scope.row.visitState!==2"
                             v-if="permissionsArr.includes('system:register:edit')"
                  >
                    修改
                  </el-button>
                  <el-button type="warning" :disabled="scope.row.regState !== 0" @click="registrationRefund(scope.row)"
                             size="mini">
                    {{ scope.row.loading ? '处理中...' : '退款' }}
                  </el-button>
<!--                  <el-button
                      type="danger"
                      :disabled="scope.row.regState !== 0 || scope.row.visitState === 6"
                      @click="registrationCancellation(scope.row)"
                      size="mini"
                  >
                    {{ scope.row.loading ? '处理中...' : '作废' }}
                  </el-button>-->
                </div>
              </template>

            </el-table-column>
          </el-table>
        </div>

        <div class="dialog">
          <el-dialog title="挂号详情"
                     :close-on-click-modal="false" :visible.sync="showModalVisible" class="showDialog" width="50%">
            <div class="aform">
              <!-- 表单 -->
              <el-form :model="showForm" label-width="90px" size="mini" disabled="disabled">
                <el-row :gutter="4">
                  <el-col :span="v.spanRows" type="flex" v-for="(v,i) in showType" :key="i">
                    <!-- input -->
                    <el-form-item v-if="v.type === 'input'" :label="v.label" style="white-space: nowrap">
                      <el-input :suffix-icon='v.prefix' v-model="$data.showForm[v.modelValue]">
                      </el-input>
                    </el-form-item>

                    <el-form-item v-if="v.type === 'select'" :label="v.label" style="white-space: nowrap">
                      <el-select v-model="$data.showForm[v.modelValue]" filterable
                                 :placeholder="$data.showForm[v.modelValue] ? '' : ' '">
                        <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
                          <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 将按钮放在el-form内部，使用el-form-item控制位置 -->
                <el-form-item style="text-align: right; margin-top: 20px; margin-bottom: 0">
                  <el-button :disabled="false" type="warning" size="mini" @click="handleCancelShow">取消</el-button>
                </el-form-item>
              </el-form>
            </div>

          </el-dialog>
          <div/>

          <el-dialog title="修改挂号信息"
                     :visible.sync="editModalVisible"
                     class="editModalVisible"
                     width="25%">
            <div class="aform">
              <el-form :model="editForm" label-width="90px" size="mini">
                <!-- 第一行：挂号类别 -->
                <el-form-item label="挂号类别:">
                  <el-select v-model="editForm.regTypeId" style="width: 100%" disabled>
                    <el-option v-for="item in regOptions" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>

                <!-- 第二行：挂号日期和时段 -->
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="挂号日期:">
                      <el-input v-model="editForm.regDate" disabled></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="时段:">
                      <el-select v-model="editForm.timeFrame" placeholder="请选择时段" style="width:100%"
                                 @change="getActiveList">
                        <el-option v-for="item in timeFrameOption" :key="item.id" :label="item.label" :value="item.id"
                                   :disabled="item.id < currentTimeFrame"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="当前科室:">
                      <el-select v-model="editForm.currentDept" style="width:100%" @change="getActiveList" disabled>
                        <el-option v-for="item in allDeptOptions" :key="item.id" :label="item.label"
                                   :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="当前医生:">
                      <el-select v-model="editForm.currentDoctor" style="width:100%" @change="getActiveList" disabled>
                        <el-option v-for="item in doctorOptions" :key="item.id" :label="item.label"
                                   :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>


                <!-- 第三行：挂号科室 -->
                <el-form-item label="挂号科室:">
                  <el-select v-model="editForm.regDepId" placeholder="请选择科室" style="width:100%"
                             @focus="getActiveList">
                    <el-option v-for="item in deptOptions" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>

                <!-- 第四行：挂号医生 -->
                <el-form-item label="挂号医生:">
                  <el-select v-model="editForm.regDoctorId" placeholder="请选择医生" style="width:100%"
                             @focus="getActiveList2">
                    <el-option v-for="item in doctorOptions" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>

            <div slot="footer" class="dialog-footer">
              <el-button size="mini" @click="handleCancelEditReservatione">取消</el-button>
              <el-button size="mini" type="primary" @click="editRegister">确定</el-button>
            </div>
          </el-dialog>
        </div>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[8, 16, 24]"
            :page-size="pageSize"
            :total="totalSize"
            layout="total, sizes, prev, pager, next, jumper"
            background>
          >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getAllDept,
  getAllReservation,
  getDoctorList,
  getRegisterType,
  registrationRefund
} from "@/api/reservation/reservationList";
import ShowType from './reservationListType.js'
import dayjs from "dayjs";
import {editRegisterList, getActiveList} from "@/api/reservation/reservation";
import {withLoading} from "@/untils/loading";

export default {
  inject: ['reload'], // 无痕刷新
  components: {},
  data() {
    const currentHour = dayjs().hour();
    const currentTimeFrame = currentHour < 12 ? 1 : (currentHour < 18 ? 2 : 3);
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 树菜单Props
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // str
      windowWidth: '', //右侧表格动态宽度
      searchValue: '',
      CatalogueName: '挂号列表',
      DropDownedName: '全部',
      state: 0,
      iconComes: 'el-icon-byj',
      // boolean
      disabled: true,
      getdisabled: true,
      loading: false,
      addModelShow: false, // 新增控制
      showModalVisible: false,
      editModalVisible: false,
      // number
      idx: 0,
      pageNum: 1, //当前页currentPage
      pageSize: 8,
      totalSize: 10, //总条数
      regState: null,
      /* obj */
      addForm: {}, // form表单 新增 *
      editForm: {
        id: null,
        regDepId: null,
        regDoctorId: null,
        regTypeId: null,
        regDate: null,
        timeFrame: currentTimeFrame,
        currentDoctor: null,
        currentDept: null,
      },
      // arr
      data: [],
      userInfo: [],
      tableData: [],
      currentTable: [],
      showType: [],
      TypeOption: [
        {id: 1, label: '西药', value: '西药'}, {id: 2, label: '中成药', value: '中成药'},
        {id: 3, label: '卫材', value: '卫材'}, {id: 4, label: '血液', value: '血液'},
        {id: 5, label: '疫苗', value: '疫苗'}, {id: 9, label: '中药', value: '中药'}
      ],
      formType: [], // 表单头部内容
      timeFrameOption: [{id: 1, label: '上午'}, {id: 2, label: '下午'}, {id: 3, label: '晚上'}],
      statusOption: [{id: 0, label: '禁用', value: '禁用'}, {id: 1, label: '可用', value: '可用'}],
      // title右侧按钮
      headerBtn: [
        {search: "search", title: "搜索", type: "success", style: {marginLeft: "-20px"}},
      ],
      feetBtn: [
        // { refesh:"refesh", label:"新增", type:"primary", icon:"el-icon-edit" },
        // { refesh:"refesh", label:"修改", type:"primary", icon:"el-icon-finished" },
        // { refesh:"refesh", label:"删除", type:"primary", icon:"el-icon-document-checked" },
        // { refesh:"refesh", label:"查看", type:"primary", icon:"el-icon-sort" },
        // { refesh:"refesh", label:"打印", type:"primary", icon:"el-icon-printer" },
        // { refesh:"refesh", label:"导出", type:"primary", icon:"el-icon-finished" },
        // { refesh:"refesh", label:"关闭", type:"primary", icon:"el-icon-close" },
      ],
      // title右侧按钮
      payTypeOptions: [{id: 1, label: '现金'}, {id: 2, label: '支付宝'}, {id: 3, label: '微信'},
        {id: 4, label: '银行卡'}, {id: 5, label: '医保'}, {id: 6, label: '优惠支付'},
        {id: 7, label: '健康卡支付'}, {id: 8, label: '聚合支付'}, {id: 9, label: '组合支付'},
      ],
      payStateOptions: [{id: 0, label: '否'}, {id: 1, label: '是'}],
      tableRows: [
        {name: "系统序号", prop: "id"}, {name: "挂号单据编号", prop: "docNo"}, {name: "姓名", prop: "name"},
        {name: "挂号时间", prop: "optTime"}, {name: "挂号科室", prop: "regDepId", op: 'deptOptions'},
        {name: "挂号医生", prop: "regDoctorId", op: 'doctorOptions'},
        {name: "挂号类型", prop: "regTypeId", op: 'regOptions'}, {
          name: "挂号状态",
          prop: "regState",
          op: 'regStateOption'
        },
        {name: "挂号方式", prop: "regMode", op: 'regModeOption'}, {
          name: "挂号进度",
          prop: "visitState",
          op: 'visitStateOption'
        },
        {name: "应收金额", prop: "receivedMoney"}, {name: "实收金额", prop: "receivableMoney"},
        {name: "支付状态", prop: "payState", op: 'payStateOptions'}, {
          name: "支付方式",
          prop: "payType",
          op: 'payTypeOptions'
        },
        {name: "优惠金额", prop: "discountMoney"}
      ],
      visitStateOption: [{id: 1, label: '待签到'}, {id: 2, label: '待就诊'}, {id: 3, label: '已接诊'}, {
        id: 4,
        label: '已取消'
      }, {id: 5, label: '待分诊'}, {id: 6, label: '已退款'}],
      regModeOption: [
        {id: 1, label: '窗口'}, {id: 2, label: '诊间'}, {id: 3, label: '自助'},
        {id: 4, label: '预约'}, {id: 5, label: '自动'}, {id: 6, label: '收费'},
        {id: 7, label: '微信'}, {id: 8, label: 'APP'}, {id: 9, label: '分诊'}, {id: 99, label: '体检接口使用'}
      ],
      regStateOption: [{id: 0, label: '未作废'}, {id: 1, label: '已作废原单'}, {id: 2, label: '作废负单'}],
      payTypeOption: [{id: '1', label: '现金'}, {id: '2', label: '支付宝'}, {id: '3', label: '微信'}, {
        id: '4',
        label: '银行卡'
      }, {id: '5', label: '医保'}, {id: '6', label: '优惠支付'}, {id: '7', label: '健康卡支付'}],
      regOptions: [],
      doctorOptions: [],
      allDeptOptions: [],
      deptOptions: [],
      roleOptions: [],
      queryConditionForm: {
        name: '',
        timeFrameArr : [
          dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),  // 当天 00:00:00
          dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')    // 当天 23:59:59
        ]
      },
      // 表单验证规则
      addFormRules: {},
      showForm: {
        createTime: '',
        discountMoney: null,
        docNo: null,
        id: null,
        name: '',
        nullifyReason: '',
        nullifyRegId: null,
        nullifyTime: '',
        nullifyUserId: null,
        optTime: '',
        orderId: null,
        patientId: null,
        payState: '',
        payType: null,
        receivableMoney: null,
        receivedMoney: null,
        regDepId: null,
        regDoctorId: null,
        regMode: null,
        regNum: null,
        regState: null,
        regTime: '',
        regTypeId: null,
        regUserId: null,
        remake: '',
        utyTimeDetailsId: null,
        visitId: null,
        visitState: null,
      },
      permissionsArr: [],
      elTree: [
        {
          label: '全部', path: '', title: '', icon: 'el-icon-news',
          children: [],
        },
      ],
    };
  },
  computed: {
    currentTimeFrame() {
      const hour = dayjs().hour();
      return hour < 12 ? 1 : (hour < 18 ? 2 : 3);
    }
  },
  mounted() {
    this.showType = ShowType.map(function (v) {
      return v
    })
    this.permissionsArr = JSON.parse(localStorage.getItem('permissions'))
    this.getAllDept();
    this.handleGetDoctorList();
    this.loadData();
    this.getRegisterType();
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })


  },
  methods: {
    async getAllDept() {
      const res = await getAllDept()
      this.allDeptOptions = res.data.map(item => {
        return {id: item.id, label: item.deptName}
      })
      console.log(this.allDeptOptions, 'allDeptOptionsallDeptOptionsallDeptOptionsallDeptOptions')
    },

    async handleCancelEditReservatione() {
      await this.loadAllDept();
      await this.handleGetDoctorList();
      this.editForm = Object.assign({}, this.$options.data.call(this).editForm)
      this.editModalVisible = false;
    },
    async editRegister() {
      await withLoading(this, '数据提交中...')(async () => {
        const res = await editRegisterList(this.editForm);
        if (res.code === 200) {
          await this.loadData();
          this.editModalVisible = false;
        } else {
          this.$message.error(res.message)
        }
      });
    },
    async getActiveList2() {
      const res = await getActiveList({
        regTime: this.editForm.regDate,
        type: this.editForm.timeFrame,
        deptId: this.editForm.regDepId,
      });
      this.doctorOptions = res.data.map(item => {
        return {
          id: item.doctorId, label: item.doctorName
        }
      })
    },
    async getActiveList() {
      const res = await getActiveList({
        regTime: this.editForm.regDate,
        type: this.editForm.timeFrame,
      });
      const registertype = res.data.filter(item => item.registertypeId === this.editForm.regTypeId)
      this.deptOptions = registertype
          .filter((dept, index, arr) =>
              arr.findIndex(d => d.deptId === dept.deptId) === index
          ).map(item => ({
            id: item.deptId,
            label: item.deptName,
          }));
      this.editForm.regDoctorId = null;
    },
    editReservation(row) {
      this.editForm.currentDept = row.regDepId;
      this.editForm.currentDoctor = row.regDoctorId;
      this.editForm.id = row.id;
      this.editForm.regTypeId = row.regTypeId;
      this.editForm.regDate = dayjs().format('YYYY-MM-DD');
      this.editForm = {...this.editForm, ...row};
      this.editForm.regDepId = null;
      this.editForm.regDoctorId = null;
      this.getActiveList();
      this.editModalVisible = true;
    },

    async registrationCancellation(row) {
      const confirmResult = await this.$confirm(
          `是否确认作废挂号人 【${row.name}】的挂号订单?`,
          '作废确认',
          {
            confirmButtonText: '确认作废',
            cancelButtonText: '取消',
            type: 'warning'
          }
      )

      if (!confirmResult) return;
      await withLoading(this, '作废处理中...')(async () => {
        const newData = JSON.parse(JSON.stringify(row))
        newData.visitState = 4;
        const res = await editRegisterList(newData);
        if (res.code === 200) {
          await this.loadData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    async registrationRefund(row) {
      try {
        // 1. 确认弹窗
        const confirmResult = await this.$confirm(
            `是否确认退款挂号人 【${row.name}】的挂号订单?`,
            '退款确认',
            {
              confirmButtonText: '确认退款',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        if (!confirmResult) return;
        await withLoading(this, '退款处理中...')(async () => {
          const res = await registrationRefund({
            id: row.id,
            type: [8, 9].includes(row.payType) ? 1 : 2
          });

          // 4. 处理结果
          if (res.code === 200) {
            await this.loadData(); // 刷新数据
          } else {
            this.$message.error(res.message || '退款失败');
          }
        });


      } catch (error) {

      } finally {
      }
    },
    async handleConditionQuery() {
      try {
        const res = await getAllReservation({
          pageSize: this.pageSize,
          pageNum: this.pageNum,
          condtion: this.queryConditionForm.name || '',  // name为空时传空字符串
          startTime: this.queryConditionForm.timeFrameArr?.[0] || '',  // 使用可选链更安全
          endTime: this.queryConditionForm.timeFrameArr?.[1] || '',    // 使用可选链更安全
          regState: this.regState ?? null
        });
        if (res.code === 200) {
          this.totalSize = res.data.totalSize;
          this.tableData = res.data.content.map(item =>{return{
            ...item,
            payType:parseInt(item.payType),
          }});
        } else {
          this.$message.error("系统异常:请联系管理员")
        }
      } catch (error) {
        this.$message.error("系统异常:请联系管理员")
      } finally {

      }
    },

    async handleGetDoctorList() {
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, label: item.fullName}
      })
    },

    async getRoleList() {
      const res = await getDoctorList()
      this.roleOptions = res.data.map(item => {
        return {id: item.id, label: item.fullName}
      })
      console.log(res, 'getDoctorListgetDoctorList')
    },

    handleCancelShow() {
      this.showForm = {};
      this.showModalVisible = false;
    },


    handleDbShowData(row) {
      console.log(row, 'rowrow')
      this.showForm = row;
      this.handleGetDoctorList();
      this.getRegisterType();
      this.getRoleList();
      this.showModalVisible = true;
    },

    async getRegisterType() {
      if (this.regOptions.length > 0) return;
      const res = await getRegisterType();
      this.regOptions = res.data.map(item => {
        return {label: item.designation, id: item.id}
      })
    },

    async loadAllDept() {
      const res = await getAllDept();

      const departmentNodes = res.data.map(dept => ({
        label: dept.deptName,      // 科室名称（显示文本）
        id: dept.id,           // 科室ID（用于后续查询医生）
      }));

      this.deptOptions = res.data.map(item => {
        return {
          id: item.id, label: item.deptName
        }
      })

      this.elTree = [
        {
          label: '全部',
          path: '',
          icon: 'el-icon-news',
          children: departmentNodes // 将科室作为"全部"的子节点
        }
      ];
    },
    /*
      数据源
    */
    async loadData() {
      const newItem = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        condtion: this.queryConditionForm.name || '',
        startTime: this.queryConditionForm.timeFrameArr?.[0] || '',
        endTime: this.queryConditionForm.timeFrameArr?.[1] || '',
        regState: this.regState ?? null
      }
      try {
        let res = await getAllReservation(
            newItem
        );
        if (res.code === 200) {
          this.totalSize = res.data.totalSize;
          this.tableData = res.data.content.map(item =>{return{
            ...item,
            payType : parseInt(item.payType)
          }});
        } else {
          this.$message.error("系统异常:请联系管理员")
        }
      } catch (error) {
        this.$message.error("系统异常:请联系管理员")
      } finally {
      }
    },
    /*
      about tree
    */
    handleNodeClick(data, e) {
      this.loadData()
    },

    // SelectVal to editForm
    // col 里面包含了表头字段和名称，list 是表格数据
    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 40; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串
      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 12; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 8;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 32;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    // 步骤
    handClick(i) {
      // i event
      switch (i) {
        case 0:
          this.loadData();
          break;
      }
    },
    handleCommand(command) {
      this.DropDownedName =
          command === 'c' ? '未作废' :
              command === 'a' ? '已作废原单' :
                  command === 'b' ? '作废负单' :
                      '全部';
      const state =
          command === 'c' ? 0 :
              command === 'a' ? 1 :
                  command === 'b' ? 2 :
                      null;
      this.regState = state !== null ? parseInt(state) : null;
      this.loadData();
    },

    feetHandClick(i) {
      console.log(i)
      switch (i) {
        case 0:

          break;
        case 1:

          break;
        case 2:
          break;
        case 3:

          break;
        case 4:

          break;
        case 5:
          break;
      }
    },

    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 328;
    },


    //分页
    //每页条数改变触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.loadData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadData();
    },
    getColumnWidth(label, prop, tableData) {
      const minWidth = 100;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },
    safeGetMappedValue(col, row, type) {

      const hiddenProps = new Set([
        'usedfrquId', 'sdoseCnt', 'prdCnt', 'prdDays', 'medcWayId', 'tcmCnt',
        'selfProe', 'skintstRslt', 'remark', 'remarks', 'rxDosCnt',
      ]);

      if (hiddenProps.has(col.prop)) {
        return ''; // 直接返回空字符串，不显示
      }
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id == rawValue);
      return matched?.label || rawValue;
    },
    /*表格合计列计算*/
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'receivableMoney': '实收金额',
        'receivedMoney': '应收金额',
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },
  },

}
</script>

<style lang="less" scoped>
/deep/ .el-dialog__header {
  padding: 18px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.dialog {
  .showDialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }
}


// content
.MedicenCata {
  height: 100%;
  width: 100%;
  // header
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    // justify-content: space-evenly;
    // icon
    .header-icon {
      display: flex;
      align-items: center;
    }

    .feetbtn {
      display: flex;
      justify-content: center;
      margin-left: 12px;
    }
  }

  // main
  .main {
    width: 100%;
    display: flex;
    justify-content: space-between;
    // height: 473px; /* 设置父容器的高度 */
    // overflow-y: auto; /* 当内容超出容器高度时显示垂直滚动条 */
    // left

    // right
    .main-right {
      flex: 1;
      width: 100%;
      height: 100%;
      // alert
      .addmessagesBox {
        .tabs {
          /deep/ .el-select > .el-input {
            width: 172px;
          }

          /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
            width: 172px;
          }

          /deep/ .el-form-item__content {
            display: flex;

            span {
              font-size: 12px;
            }
          }

          .oneLine {
            width: 524px;
            // background-color: indianred;
          }
        }

        /deep/ .el-dialog__title {
          font-size: 12px;
        }

        /deep/ .el-table {
          font-size: 12px;
        }

      }

      // icon
      .main-icon {
        display: flex;
        align-items: center;
        padding: 12px;
        line-height: 40px;

        .main-icon-a {
          // width: 240px;
          // background-color: #00557f;
        }

        .main-icon-b {
          margin-left: 20px;

          /deep/ .el-dropdown {
            font-size: 12px;
            cursor: pointer;
          }

          /deep/ .el-dropdown:hover {
            font-weight: bold;
            color: #66b1ff;
          }

          /deep/ .el-icon--right {
            // background-color: #66b1ff;
          }

          /deep/ .el-popper[x-placement^=bottom] {
            margin-top: 0;
          }
        }

        // c
        .main-icon-c {
          display: flex;
          margin-left: 28px;

          /deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b] {
            width: 80%;
          }
        }
      }

      // table
      /deep/ .el-table .cell {
        font-size: 12px;
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div :first-child {
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div {
        text-align: center;
        overflow: hidden;
        white-space: normal;
        word-break: break-all;
      }

      .table {

      }
    }
  }

  // addModel
  .addModel {
    margin-left: 12px;

    /deep/ .el-dialog__header {
      padding: 12px;
      line-height: 28px;
      background-color: #007bb0;
    }

    /deep/ .el-dialog__title {
      color: #fff;
      font-size: 12px;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close:hover {
      background-color: brown;
    }

    /deep/ .el-form-item__label {
      font-size: 12px;
    }
  }

  .editModel {
    /deep/ .el-dialog__header {
      padding: 12px;
      line-height: 28px;
      background-color: #007bb0;
    }

    /deep/ .el-dialog__title {
      color: #fff;
      font-size: 12px;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close:hover {
      background-color: brown;
    }

    /deep/ .el-form-item__label {
      font-size: 12px;
    }
  }

  // feet
  .feet {
    padding: 12px;

  }

}
</style>